package com.atguigu.gulimall.product.service.impl;

import com.atguigu.gulimall.product.entity.CategoryBrandRelationEntity;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子关系的树形结构
        //2.1、找到所有的一级分类（parentCid == 0）
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity -> //过滤出一级分类
//          categoryEntity.getParentCid().equals(0L) //Long类型值比较要注意
                        categoryEntity.getParentCid() == 0
        ).map((menu) -> { //遍历每一个一级分类，设置其子分类
            menu.setChildren(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> { //按数据库字段sort排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> ids) {
        //TODO 1、检测当前删除的菜单，是否被别的地方引用

        baseMapper.deleteBatchIds(ids);// 逻辑删除
    }

    /**
     * 根据分类id获取完整路径
     *
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        findParentPath(catelogId, paths);

        Collections.reverse(paths);

        return paths.toArray(new Long[paths.size()]);
    }

    private void findParentPath(Long catelogId, List<Long> paths) {
        //把当前id加入列表
        paths.add(catelogId);

        CategoryEntity entity = this.getById(catelogId);
        if (entity.getParentCid() != 0) {
            findParentPath(entity.getParentCid(), paths);
        }
    }

    /**
     * 递归查找所有菜单的子菜单
     *
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        return all.stream().filter(categoryEntity ->
                root.getCatId().equals(categoryEntity.getParentCid())
        ).map(menu -> {   //找到子菜单
            menu.setChildren(getChildren(menu, all));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> //菜单的排序
                (menu.getSort() == null ? 0 : menu.getSort()))
        ).collect(Collectors.toList());
    }

    @Override
    @Transactional //事务提交
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);

        //保证冗余字段的数据一致: pms_category_brand_relation#catelog_name
        if(!StringUtils.isEmpty(category.getName())){
            //同步更新其他关联表中的数据
            categoryBrandRelationService.updateCategoryName(category.getCatId(),category.getName());

            //TODO 更新其他
        }
    }
}